package cn.maszy.action.systemsetting;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import net.sourceforge.stripes.action.SessionScope;

import org.apache.commons.lang.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import test.LoadExcel;
import cn.maszy.common.BaseAction;
import cn.maszy.common.DateUtils;
import cn.maszy.common.Pager;
import cn.maszy.common.Transcoding;
import cn.maszy.model.systemsetting.B_T_Ufp_Category;
import cn.maszy.model.systemsetting.B_T_Ufp_Material;
import cn.maszy.model.systemsetting.B_T_Ufp_MaterialCategory;
import cn.maszy.model.systemsetting.B_T_Ufp_Project;
import cn.maszy.service.systemsetting.B_T_Ufp_MaterialCategoryService;
import cn.maszy.service.systemsetting.B_T_Ufp_MaterialService;

@SessionScope
public class MaterialAction extends BaseAction<B_T_Ufp_Material> {
	/**
	 * 版本控制信息
	 */
	  //上传所需
	private static final int BUFFER_SIZE = 1024 * 1024;
	private File myFile;// 上传的文件
	private String fileName;// 文件上传时的名字
	private String imageFileName;// 给文件随机产生的名字，方便与存放，未用
	private String caption;// 显示图片时自己输入的名字
	private File imageFile;
	private B_T_Ufp_MaterialCategory b_T_Ufp_MaterialCategory;
	//是否可以修改价格
	private String isupdate;
	@Autowired
	private B_T_Ufp_MaterialCategoryService b_T_Ufp_MaterialCategoryService;
	private static final long serialVersionUID = 6179604301571294802L;
	private B_T_Ufp_Material b_T_Ufp_Material;
	private List<B_T_Ufp_Material> list_b_T_Ufp_Material;
	@Autowired
	private B_T_Ufp_MaterialService b_T_Ufp_MaterialService;
	private String checkIds;
	private String flag;
	private List<B_T_Ufp_Material> b_T_Ufp_MaterialList;
	//用于传递我的工程时 给具体部位增加数据时，传递uuid和那么给他的子类。
	private String positiontype;
	/*******************STRUTS ACTION METHOD*************************/
	public String materialDelete() throws Exception {
		int i=b_T_Ufp_MaterialService.delete(checkIds);
		if(i>0)
			if(b_T_Ufp_Material.getCategoryStatus().equals("0"))
			{
				return ajaxForwardSuccess(getText("msg.operation.success"), "","materialList", "", "");
			}
			else
			{
				return ajaxForwardSuccess(getText("msg.operation.success"), "","materialListH", "", "");
			}
		return ajaxForwardError(getText("msg.operation.failure"));
	}
	public String materialUpdate() throws Exception {
		int i=b_T_Ufp_MaterialService.update(b_T_Ufp_Material);
		if(i>0)
			if(b_T_Ufp_Material.getCategoryStatus().equals("0"))
			{
				return ajaxForwardSuccess(getText("msg.operation.success"), "","materialList", "closeCurrent", "");
			}
			else
			{
				return ajaxForwardSuccess(getText("msg.operation.success"), "","materialListH", "closeCurrent", "");
			}
		return ajaxForwardError(getText("msg.operation.failure"));
	}
	public String materialList() throws Exception {
		if(b_T_Ufp_Material!=null&&!"".equals(b_T_Ufp_Material))
		{
			flag =Transcoding.getcode(request, flag);
//			flag =new String(flag.getBytes("ISO8859_1"),"GBK");
			String flag1[]=flag.split(",");
			b_T_Ufp_Material.setCategoryName(flag1[0]);
			b_T_Ufp_Material.setCategoryUuid(flag1[1]);
			b_T_Ufp_Material.setCategoryStatus(flag1[2]);
		}
		else
		{
			if(flag !=null||!"".equals(flag))
			{
				flag =Transcoding.getcode(request, flag);
//				flag =new String(flag.getBytes("ISO8859_1"),"GBK");
				String flag1[]=flag.split(",");
				b_T_Ufp_Material = new B_T_Ufp_Material();
				b_T_Ufp_Material.setCategoryName(flag1[0]);
				b_T_Ufp_Material.setCategoryUuid(flag1[1]);
				b_T_Ufp_Material.setCategoryStatus(flag1[2]);
			}
		}
		pager = new Pager<B_T_Ufp_Material>(pageNum, numPerPage,orderField,orderDirection);
		pager= b_T_Ufp_MaterialService.selectList(b_T_Ufp_Material,pager);
		return SUCCESS;
	}
	//我的工程自购材料用
	public String materialRecycling() throws Exception {
		if(b_T_Ufp_Material!=null&&!"".equals(b_T_Ufp_Material))
		{
			flag =Transcoding.getcode(request, flag);
//			flag =new String(flag.getBytes("ISO8859_1"),"GBK");
			String flag1[]=flag.split(",");
			b_T_Ufp_Material.setCategoryName(flag1[0]);
			b_T_Ufp_Material.setCategoryUuid(flag1[1]);
			b_T_Ufp_Material.setCategoryStatus(flag1[2]);
		}
		else
		{
			if(flag !=null||!"".equals(flag))
			{
				flag =Transcoding.getcode(request, flag);
//				flag =new String(flag.getBytes("ISO8859_1"),"GBK");
				String flag1[]=flag.split(",");
				b_T_Ufp_Material = new B_T_Ufp_Material();
				b_T_Ufp_Material.setCategoryName(flag1[0]);
				b_T_Ufp_Material.setCategoryUuid(flag1[1]);
				b_T_Ufp_Material.setCategoryStatus(flag1[2]);
			}
		}
		pager = new Pager<B_T_Ufp_Material>(pageNum, numPerPage,orderField,orderDirection);
		list_b_T_Ufp_Material= b_T_Ufp_MaterialService.select(b_T_Ufp_Material);
		return SUCCESS;
	}
	public String materialDetail() throws Exception {
		if(b_T_Ufp_Material==null){
			b_T_Ufp_Material=b_T_Ufp_MaterialService.selectOne("");
			if(flag !=null||!"".equals(flag)){
				b_T_Ufp_Material = new B_T_Ufp_Material();
				flag =Transcoding.getcode(request, flag);
//				flag =new String(flag.getBytes("ISO8859_1"),"GBK");
				String flag1[]=flag.split(",");
				b_T_Ufp_Material.setCategoryName(flag1[0]);
				b_T_Ufp_Material.setCategoryUuid(flag1[1]);
				b_T_Ufp_Material.setCategoryStatus(flag1[2]);
				}
//			b_T_Ufp_Material=new B_T_Ufp_Material();
//			b_T_Ufp_Material.setStatus(status);
		}else{
			b_T_Ufp_Material=b_T_Ufp_MaterialService.selectOne(b_T_Ufp_Material.getUuid());
		}
		return SUCCESS;
	}
	
	public String materialImport() throws Exception {
		//上传
//		 imageFileName = new Date().getTime() + getExtention(fileName);
		 String file = ServletActionContext.getServletContext().getRealPath(
		 "/zy-admin/Download");
		 if(fileName==null ||myFile==null)
		 {
			 return ajaxForwardError("请先选择文件");
		 }
		 imageFile = new File(file + "/" + fileName);// 图片存放的地址
		 copy(myFile, imageFile);// 一切都设置好后，就将图片放在imageFile下
		 //记录当前时间。
		 String nowTime =DateUtils.nows();
		//导入
		String adress = file+"\\"+fileName;
		String message=getExcelContent(adress);
		if(!"success".equals(message)){
			return ajaxForwardError(message);
		}
		int ok=0;
		List<B_T_Ufp_Material> list=this.getB_T_Ufp_MaterialList();
		for(int i= 0;i<list.size();i++)
		{	
			b_T_Ufp_Material = list.get(i);
			//插入数据
			ok=b_T_Ufp_MaterialService.update(b_T_Ufp_Material);
			if (ok == 0)
			{
				//执行删除以前的数据
				b_T_Ufp_MaterialService.deleteByCreatetime(nowTime,flag);
				return ajaxForwardSuccess(getText("导入成功"+(list.size()-1)+"行"), "","", "", "");
			}
		}
		if (ok>0);
		//执行删除以前的数据
		b_T_Ufp_MaterialService.deleteByCreatetime(nowTime,flag);
		return ajaxForwardSuccess(getText("导入成功"+(list.size()-1)+"行"), "","", "", "");
	}
	/**
	 * 根据文件路径读取excel
	 *解析excel数据封装进list
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public String  getExcelContent(String fileName) throws IOException {
		List<B_T_Ufp_Material> dataList = new ArrayList<B_T_Ufp_Material>();
		// 构造 XSSFWorkbook 对象，strPath 传入文件路径
		boolean isExcel2003 = true;
		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
			isExcel2003 = false;
		}
		File file = new File(fileName);
		FileInputStream inputStream = new FileInputStream(file);
		Workbook wb = isExcel2003 ? new HSSFWorkbook(inputStream)
				: new XSSFWorkbook(inputStream);
		// 读取第一章表格内容
		Sheet sheet = wb.getSheetAt(0);
		// 定义 row、cell
		Row row;
		// 循环输出表格中的内容
//		System.out.println(sheet.getFirstRowNum()+"   \t"+sheet.getLastRowNum());
		for (int i = sheet.getFirstRowNum()+1; i < sheet.getLastRowNum() + 1; i++) {
			row = sheet.getRow(i);
			if (row != null) {
				// 循环列
				B_T_Ufp_Material b_T_Ufp_Material=new B_T_Ufp_Material();
				//for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
				for (int j = row.getFirstCellNum(); j < 10; j++) {
					Cell cell = row.getCell(j);
					String cellValue =formatStr(cell);
					if(j==1)
					{
						b_T_Ufp_Material.setCategoryName(cellValue);
						//取出类别。并查询出uuid并设置给对象b_T_Ufp_Project
						b_T_Ufp_MaterialCategory = new B_T_Ufp_MaterialCategory();
						b_T_Ufp_MaterialCategory.setCategoryName(cellValue);
						b_T_Ufp_MaterialCategory.setCategoryStatus(flag);
						List <B_T_Ufp_MaterialCategory> list_b_T_Ufp_MaterialCategory =b_T_Ufp_MaterialCategoryService.select(b_T_Ufp_MaterialCategory);
						if(list_b_T_Ufp_MaterialCategory.size()<1)
						{
							return "excel中项目小类《"+cellValue+"》系统中未找到匹配项："+"第"+(i+1)+"行";
						}
						String uuid =list_b_T_Ufp_MaterialCategory.get(0).getUuid();
						b_T_Ufp_Material.setCategoryUuid(uuid);
						b_T_Ufp_Material.setCategoryStatus(flag);
					}
					else if(j==2)
					{
						b_T_Ufp_Material.setMaterialName(cellValue);
					}
					else if(j==3)
					{
						b_T_Ufp_Material.setMaterialBrand(cellValue);
					}
					else if(j==4)
					{
						b_T_Ufp_Material.setMaterialModel(cellValue);
					}
					else if(j==5)
					{
						b_T_Ufp_Material.setFinishes(cellValue);
					}
					else if(j==6)
					{
						b_T_Ufp_Material.setUnit(cellValue);
					}
					else if(j==7)
					{	if(!"".equals(cellValue))
						{//如果不是数字
							if(!NumberUtils.isNumber(cellValue))
							{
								return "客户报价请填写数字"+"第"+(i+1)+"行";
							}
							float f = Float.parseFloat(cellValue);
							b_T_Ufp_Material.setAngebotspreis(f); 
						}
						else
						{
							b_T_Ufp_Material.setAngebotspreis((float) 0);
						}
					}
					else if(j==8)
					{
						b_T_Ufp_Material.setProducter(cellValue);
					}
				}
				dataList.add(b_T_Ufp_Material);
			}
		}
		this.setB_T_Ufp_MaterialList(dataList);
		return "success";
	}
	public String formatStr(Cell cell){
		if(cell ==null)
		{
			return "";
		}
		String cellValue="";
		/** 处理数字型的,自动去零 */
		if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
			/** 在excel里,日期也是数字,在此要进行判断 */
			if (HSSFDateUtil.isCellDateFormatted(cell)) {
				SimpleDateFormat simpleDateFormate = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				cellValue = simpleDateFormate.format(cell
						.getDateCellValue());
			} else {
				cellValue =cell.getNumericCellValue()+ "";
			}
		}
		/** 处理字符串型 */
		else if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
			cellValue = cell.getStringCellValue();
		}
		/** 处理布尔型 */
		else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
			cellValue = cell.getBooleanCellValue() + "";
		}
		/**处理公式**/
		else if (Cell.CELL_TYPE_FORMULA == cell.getCellType()) {
			cellValue = String.valueOf(cell.getNumericCellValue());  
		}
		/** 其它的,非以上几种数据类型 */
		else {
			cellValue = cell.toString() + "";
		}
		return cellValue;
	}
	
	
	public void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				byte[] buf = new byte[in.available()];

				if (in.available() < BUFFER_SIZE && in.available() > 0) {
					in.read(buf);
					out.write(buf);
				}
				while (in.available() >= BUFFER_SIZE) {
					in.read(buffer);
					out.write(buffer);
					if (in.available() < BUFFER_SIZE) {
						byte[] buff = new byte[in.available()];
						in.read(buff);
						out.write(buff);
					}
				}

			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 截取图片名字（.后的那部分）
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}
	
/********************* class set/get ****************************/
	
	public B_T_Ufp_Material getB_T_Ufp_Material() {
		return b_T_Ufp_Material;
	}

	public void setB_T_Ufp_Material(B_T_Ufp_Material b_T_Ufp_Material) {
		this.b_T_Ufp_Material = b_T_Ufp_Material;
	}
	
	public String getCheckIds() {
		return checkIds;
	}

	public void setCheckIds(String checkIds) {
		this.checkIds = checkIds;
	}

	public String getFlag() {
		return flag;
	}
	public void setFlag(String flag) {
		this.flag = flag;
	}
	public List<B_T_Ufp_Material> getList_b_T_Ufp_Material() {
		return list_b_T_Ufp_Material;
	}
	public void setList_b_T_Ufp_Material(
			List<B_T_Ufp_Material> list_b_T_Ufp_Material) {
		this.list_b_T_Ufp_Material = list_b_T_Ufp_Material;
	}
	public String getPositiontype() {
		return positiontype;
	}
	public void setPositiontype(String positiontype) {
		this.positiontype = positiontype;
	}
	public B_T_Ufp_MaterialCategory getB_T_Ufp_MaterialCategory() {
		return b_T_Ufp_MaterialCategory;
	}
	public void setB_T_Ufp_MaterialCategory(
			B_T_Ufp_MaterialCategory b_T_Ufp_MaterialCategory) {
		this.b_T_Ufp_MaterialCategory = b_T_Ufp_MaterialCategory;
	}
	public void setMyFileFileName(String fileName) {
		this.fileName = fileName;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public String getCaption() {
		return caption;
	}

	public void setCaption(String caption) {
		this.caption = caption;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public File getImageFile() {
		return imageFile;
	}

	public void setImageFile(File imageFile) {
		this.imageFile = imageFile;
	}
	public File getMyFile() {
		return myFile;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}
	public List<B_T_Ufp_Material> getB_T_Ufp_MaterialList() {
		return b_T_Ufp_MaterialList;
	}
	public void setB_T_Ufp_MaterialList(List<B_T_Ufp_Material> b_T_Ufp_MaterialList) {
		this.b_T_Ufp_MaterialList = b_T_Ufp_MaterialList;
	}
	public String getIsupdate() {
		return isupdate;
	}
	public void setIsupdate(String isupdate) {
		this.isupdate = isupdate;
	}
}
